<template>
	<div>
		<a-modal v-model='showModal' @ok='confirmOk' @cancel='cancel' :title='titles' width='70%'>
			<a-spin :spinning='loading'>
				<a-form :form='form'>
					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='商品名称' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<div style='display: flex'>
									<GoodsList ref='goodsList' @choose='choose_goods'></GoodsList>
									<a-input placeholder='请输入' v-decorator="[
                      'name',
                      {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                      },
                    ]" maxLength='30'></a-input>
									<a-button @click='selectGoods(data)' type='primary'>选择</a-button>
								</div>
							</a-form-item>
						</a-col>
						<a-col :span='12'>
							<div class='flex'>
								<a-form-item class='mb-15' label='商品分类' :label-col='labelCol' :wrapper-col='wrapperCol'>
									<div style='width: 160px'>
										<a-select class='flex-1' @change='changeSelect' placeholder='请选择'
											v-decorator="['firstCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
											<a-select-option :value='item.id' v-for='(item, index) in class_list'
												:key='index'>{{ item.name }}
											</a-select-option>
										</a-select>
									</div>
								</a-form-item>

								<div style='width: 180px'>
									<a-form-item class='mb-15'>
										<a-select class='flex-1' placeholder='请选择'
											v-decorator="['secondCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
											<a-select-option :value='item.id' v-for='(item, index) in class_list2'
												:key='index'>{{ item.name }}
											</a-select-option>
										</a-select>
									</a-form-item>
								</div>
							</div>
						</a-col>
					</a-row>
					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='商品图片' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<img v-for='(i, index) in picUrl' :key='index' :src='i'
									style='width: 102.88px; height: 102.88px' alt='avatar' />
							</a-form-item>
						</a-col>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='商品宣传视频' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<video :src='videoUrl' style='width: 100%; height: 120px' controls></video>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='库存单位' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<a-select v-decorator="[
                    'unit',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true }],
                    },
                  ]">
									<a-select-option :value='item.value' v-for='(item, index) in unitList'
										:key='index'>{{ item.label }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='所属店铺' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<a-select v-decorator="[
                    'storeId',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true, type: 'number' }],
                    },
                  ]">
									<a-select-option :value='item.id' v-for='(item, index) in store_list'
										:key='index'>{{ item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='运费' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<div style='display: flex'>
									<a-input placeholder='请输入' v-decorator="[
                      'freight',
                      {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                      },
                    ]" maxLength='30'></a-input>
									元
								</div>
							</a-form-item>
						</a-col>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='活动状态' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<a-switch checked-children='开启' un-checked-children='关闭'
									v-decorator="['status', { valuePropName: 'checked' }]" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter='[24, 0]'>
						<a-col :span='24'>
							<a-form-item class='mb-15' label='商品简介' :label-col='{ span: 4 }'
								:wrapper-col='{ span: 20 }'>
								<a-textarea placeholder='请输入' v-decorator="[
                    'introduction',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true }],
                    },
                  ]" maxLength='300'></a-textarea>
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='秒杀时段' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<a-select class='flex-1' mode='multiple' placeholder='请选择'
									v-decorator="['configIds', { rules: [{ required: true, message: '请选择' }] }]">
									<a-select-option :value='item.id'
										v-for='item in dateList'>{{ item.name }}</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='秒杀日期' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<div style='display: flex'>
									<a-range-picker
										v-decorator="['time', { rules: [{ required: true, message: '请输入', type: 'array' }] }]"
										style='width: 100%' />

								</div>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter='[24, 0]'>
						<a-col :span='12'>
							<a-form-item class='mb-15' label='排序' :label-col='labelCol' :wrapper-col='wrapperCol'>
								<a-input placeholder='请输入' type="number" v-decorator="[
                      'sort',
                      {
                        rules: [{ required: true, message: '请输入', whitespace: true,type:'any' }],
                      },
                    ]" maxLength='30'></a-input>
							</a-form-item>
						</a-col>

					</a-row>

					<div class='flex justify-between items-center'>
						<div>商品规格：</div>
						<a-button type='primary' @click='handleAdd'>添加</a-button>
					</div>
					<a-row :gutter='24'>
						<a-col :span='24'>
							<a-table class='mt-16 order-table' :columns='columns' :data-source='dataSource'
								:pagination='false'>
								<template #name='name, data, index'>
									<a-input v-model='data.name' placeholder='请输入' v-if='index == tabIndex' />
									<div v-else>{{ data.name }}</div>
								</template>
								<template #picUrl='picUrl, data, index'>
									<div class='flex items-center justify-center'>
										<a-upload v-if='index == tabIndex' list-type='picture-card'
											class='avatar-uploader' :show-upload-list='false'
											action='http://cwqd.ricecs.cn/admin-api/system/file/upload'
											:headers='{ Authorization: token }' @change='handleImg' accept=".png,.jpg">
											<img v-if='picUrl' style='width: 102.88px; height: 102.88px' :src='picUrl'
												alt='avatar' />
											<div v-else>
												<a-icon :type="loading ? 'loading' : 'plus'" />
												<div class='ant-upload-text'>Upload</div>
											</div>
										</a-upload>
										<img :src='picUrl' style='width: 102.88px; height: 102.88px' alt='avatar'
											v-if='tabIndex != index && picUrl' />

									</div>
								</template>
								<template #stock='stock, data, index'>
									<a-input v-model='data.stock' placeholder='请输入' v-if='index == tabIndex' />
									<div v-else>{{ data.stock }}</div>
								</template>
								<template #seckillPrice='seckillPrice, data, index'>
									<a-input v-model='data.seckillPrice' placeholder='请输入' v-if='index == tabIndex' />
									<div v-else>{{ data.seckillPrice }}</div>
								</template>
								<template #msPrice='msPrice, data, index'>
									<a-input v-model='data.msPrice' placeholder='请输入' v-if='index == tabIndex' />
									<div v-else>{{ data.msPrice }}</div>
								</template>

								<template #action='action, data, index'>
									<div class='flex items-center justify-center'>
										<a-button @click='onDelete(index)' class='ml-10 mr-10' type='danger'>
											删除</a-button>
										<a-button @click='handleChange(index)' class='mr-10' type='primary'
											style='background: #32cd32'>
											编辑
										</a-button>
									</div>
								</template>
							</a-table>
						</a-col>
					</a-row>
					<div class='mt-20 mb-20'>产品详情：</div>
					<a-row :gutter='24'>
						<a-col :span='24'>
							<quill-editor class='editor' v-model='content' ref='myQuillEditor' :options='editorOption'
								@blur='onEditorBlur($event)' @focus='onEditorFocus($event)'
								@change='onEditorChange($event)' @ready='onEditorReady($event)'>
							</quill-editor>
						</a-col>
					</a-row>
				</a-form>
			</a-spin>
		</a-modal>
	</div>
</template>
<script>
	import {
		quillEditor
	} from 'vue-quill-editor'
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'
	import 'quill/dist/quill.bubble.css'
	import {
		get
	} from 'lodash'
	import {
		deductionDetail,
		getBanner,
		getSpugetdetail,
		productList,
		getStoreList,
		getInfo
	} from '@/api/newPet'
	import {
		dictData,
		seckillAll,
		seckillcreate,
		seckillget,
		seckillupdate
	} from '@/api/index'
	import GoodsList from '@/components/GoodsList/index.vue'
	import dayjs from 'dayjs'

	export default {
		data() {
			return {
				count: 1,
				loading: false,
				isShow: true,
				labelCol: {
					span: 8
				},
				content: '',
				tabIndex: -1,
				editorOption: {
					placeholder: '请输入',
					theme: 'snow',
					modules: {
						toolbar: {
							container: [
								['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
								['blockquote', 'code-block'], // 引用  代码块
								[{
									header: 1
								}, {
									header: 2
								}], // 1、2 级标题
								[{
									list: 'ordered'
								}, {
									list: 'bullet'
								}], // 有序、无序列表
								[{
									script: 'sub'
								}, {
									script: 'super'
								}], // 上标/下标
								[{
									indent: '-1'
								}, {
									indent: '+1'
								}], // 缩进
								// [{ direction: 'rtl' }], // 文本方向
								[{
									size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36']
								}], // 字体大小
								[{
									header: [1, 2, 3, 4, 5, 6]
								}], // 标题
								[{
									color: []
								}, {
									background: []
								}], // 字体颜色、字体背景颜色
								// [{ font: ['songti'] }], // 字体种类
								[{
									align: []
								}], // 对齐方式
								['clean'], // 清除文本格式
								['image'] // 链接、图片，需要视频的可以加上video
							]
						}
					}
				},
				dataSource: [],
				columns: [{
						title: '规格名称',
						dataIndex: 'name',
						align: 'center',
						width: 140,
						scopedSlots: {
							customRender: 'name'
						}
					},
					{
						title: '规格图片',
						dataIndex: 'picUrl',
						width: 120,
						align: 'center',
						scopedSlots: {
							customRender: 'picUrl'
						}
					},
					{
						title: '规格库存',
						dataIndex: 'stock',
						align: 'center',
						width: 70,
						scopedSlots: {
							customRender: 'stock'
						}
					},
					{
						title: '秒杀金额（元）',
						dataIndex: 'seckillPrice',
						align: 'center',
						width: 70,
						scopedSlots: {
							customRender: 'seckillPrice'
						}
					},
					{
						title: '操作',

						dataIndex: 'action',
						width: 160,
						scopedSlots: {
							customRender: 'action'
						},
						align: 'center'
					}
					// 查看显示
					// {
					//   title: '秒杀销量',
					//   dataIndex: 'sales',
					//   align: 'center',
					//   width: 90,
					//   scopedSlots: { customRender: 'sales' },
					// },

				],
				dateList: [],
				wrapperCol: {
					span: 16
				},
				details: {},
				showModal: false,
				titles: '新增',
				info: {},
				form: this.$form.createForm(this),
				class_list: [],
				class_list2: [],
				unitList: [],
				store_list: [],
				picUrl: []
			}
		},
		computed: {},
		watch: {},
		async created() {
			await this.loadData()
		},
		components: {
			quillEditor,
			GoodsList
		},
		methods: {
			handleAdd() {
				const {
					dataSource,
					count
				} = this
				const newData = {
					name: `规格 ${count}`,
					key: count,
					picUrl: '',
					stock: '',
					seckillPrice: '',
				}
				this.count = count + 1
				this.dataSource = [...dataSource, newData]
				console.log(this.dataSource, 'xxx')
			},
			handleImg(info) {
				let fileList = [...info.fileList]
				// 2. read from response and show file link
				fileList = fileList.map((file) => {
					if (file.response) {
						this.dataSource[this.tabIndex].picUrl = file.response.data
					}
					return file
				})
			},
			handleChange(index) {
				this.tabIndex = index
			},
			getPhotos(img) {
				let list = img.split(',')
				return list[0]
			},
			async loadData() {
				const res = await seckillAll()
				this.dateList = res
				console.log(res)
			},
			// 选择商品
			selectGoods() {
				this.$refs.goodsList.open()
			},
			onEditorBlur(quill) {
				console.log('editor blur!', quill)
			},
			// 获得焦点事件
			onEditorFocus(quill) {
				console.log('editor focus!', quill)
			},
			// 准备富文本编辑器
			onEditorReady(quill) {
				console.log('editor ready!', quill)
			},
			// 内容改变事件，只需要这一个方法就够了
			onEditorChange({
				quill,
				html,
				text
			}) {
				console.log('editor change!', quill, html, text)
				this.content = html
			},
			formgetFileLength(type) {
				//获取图片
				return get(this.form.getFieldValue(type), 'length') || 0
			},
			formuploadSuccess(data, type) {
				this.form.setFieldsValue({
					images: [...this.form.getFieldValue(type), data.path]
				})
			},
			changeSelect(e) {
				console.log(e)
			},
			onChange(e) {
				console.log(e)
			},
			cancel() {
				this.form.resetFields()
				this.showModal = false
			},
			// 分类列表
			get_class(id) {
				return new Promise((resolve) => {
					productList({
						type: 0,
						spuType: this.type,
						parentId: 0
					}).then((res) => {
						resolve(res)
					})
				})
			},
			// 二级分类
			get_class2(id) {
				return new Promise((resolve) => {
					productList({
						type: 0,
						spuType: this.type,
						parentId: id
					}).then((res) => {
						resolve(res)
					})
				})
			},
			async get_store() {
				const res2 = await dictData({
					type: 'product_unit'
				})
				this.unitList = res2
				getStoreList({
					pageNo: 1,
					pageSize: 100
				}).then((res) => {
					this.store_list = res.list
				})
			},
			choose_goods(e) {
				if (e.id) {
					getSpugetdetail({
						id: e.id
					}).then((res) => {
						this.form.setFieldsValue({
							...res,
							picUrl: res.picUrl?.split(','),
							videoUrl: res.videoUrl?.split(','),
							unit: res.unit?.toString(),
							freight: res.freight?.toString()
						})
						this.spuId = res.id
						for (let i = 0; i < res.skus.length; i++) {
							res.skus[i].spuId = res.id
							res.skus[i].skuId = res.skus[i].id
						}
						this.picUrl = res.picUrl?.split(',')
						this.dataSource = res.skus
					})
				}
			},
			confirmOk() {
				this.form.validateFields((err, values) => {
					if (!err) {
						// this.loading = true
						const {
							info
						} = this
						let skus = this.dataSource
						if (values.time) {
							values.startTime = this.$utils.getStartTime(values.time[0])
							values.endTime = this.$utils.getEndTime(values.time[1])
						}
						let data = {
							id: info && info.id ? info.id : undefined,
							...this.$utils.trimValue(values),
							spuId: this.spuId,
							products: this.dataSource,
							status: values.status == true ? 1 : 0,
							products: skus,
						}
						const fun = info && info.id ? seckillupdate : seckillcreate
						fun(data)
							.then(() => {
								this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
								this.$emit('upload')
								this.cancel()
							})
							.finally(() => {
								this.loading = false
							})
					}
				})
			},
			async getDetails(id) {
				try {
					this.loading = true
					this.info = {}
					let res = await seckillget({
						id: id
					})
					this.info = res
					this.$nextTick(() => {
						this.form.setFieldsValue({
							time: [dayjs(res.startTime).format('YYYY-MM-DD'), dayjs(res.endTime)
								.format('YYYY-MM-DD')
							],
							...res,
						})
						this.dataSource = res.products?.map((i) => {
							return {
								...i,
								name: i.skuName
							}
						})
					})
					this.loading = false
				} catch (error) {
					this.loading = false
					console.log(error)
				}
			},
			getData() {
				this.loading = true
				deductionDetail({
						id: 1
					})
					.then((data) => {
						this.details = data
					})
					.finally(() => (this.loading = false))
			},
			async open(data) {
				this.info = data
				if (data.id) {
					this.titles = '修改'
					this.class_list = await this.get_class(this.type)
					this.class_list2 = await this.get_class2(data.firstCategoryId)
					this.$nextTick(async () => {
						const res = await getSpugetdetail({
							id: data.spuId
						})
						this.form.setFieldsValue({
							...res,
							picUrl: res.picUrl?.split(','),
							videoUrl: res.videoUrl?.split(','),
							unit: res.unit?.toString(),
							freight: res.freight?.toString(),
							status: data.status == 1 ? true : false
						})
						this.spuId = res.id
						for (let i = 0; i < res.skus.length; i++) {
							res.skus[i].spuId = res.id
							res.skus[i].skuId = res.skus[i].id
						}
						// this.picUrl = res.picUrl?.split(',')
						await this.getDetails(data.id)
					})

				} else {
					this.picUrl = []
					this.titles = '新增'
					this.class_list = await this.get_class(this.type)
					this.class_list2 = await this.get_class2(data.firstCategoryId)
					this.dataSource = []
				}
				this.get_store()
				this.showModal = true
				this.$nextTick(() => {
					this.form.setFieldsValue({
						time: [data.startTime, data.endTime],
					})
				})
			}
		}
	}
</script>
<style lang='less' scoped>
	/deep/ .ant-form-item-label {
		// width: 100px;
	}
</style>